<template>
  <el-form ref="form" :model="formTemp" label-width="120px">
    <el-row>
      <el-select v-model="formTemp.province" placeholder="请选择省" @change="changePro">
        <el-option v-for="item in addressData" :key="item.code" :label="item.name" :value="item.name"></el-option>
      </el-select>
      <el-select v-model="formTemp.city" placeholder="请选择市" @change="changeCity">
        <el-option v-for="item in cityData" :key="item.code" :label="item.name" :value="item.name"></el-option>
      </el-select>
      <el-select v-model="formTemp.district" placeholder="请选择区" @change="changeArea">
        <el-option v-for="item in areaData" :key="item.code" :label="item.name" :value="item.name"></el-option>
      </el-select>
      <el-input v-model="formTemp.detail" clearable placeholder="详细地址" style="width:200px;"></el-input>
    </el-row>
  </el-form>
</template>

<script lang="ts" setup>
import address from "@/utils/address.json"; //全国省市区街道数据
const addressData = ref<Array<any>>([]);
const cityData = ref<Array<any>>([]);
const areaData = ref<Array<any>>([]);
const emit = defineEmits(["update:form"]);
const props = defineProps({
  form: {
    type: Object,
    default: () => ({
      province: "",
      city: "",
      district: "",
      detail: "",
      cityCode: ""
    })
  }
});

onMounted(() => {
  // 省份数据初始化
  addressData.value = address;
});
const formTemp = computed({
  get: () => props.form,
  set: val => emit("update:form", val)
});

function changePro(e: any) {
  cityData.value = addressData.value.find(item => item.name === e)?.children || [];
  formTemp.value.district = "";
  formTemp.value.city = cityData.value[0]?.name || "";
  areaData.value = cityData.value[0]?.children || [];
  formTemp.value.district = areaData.value[0]?.name || "";
  formTemp.value.cityCode = areaData.value[0]?.code || "";
};

function changeCity(e: any) {
  areaData.value = cityData.value.find(item => item.name === e)?.children || [];
  formTemp.value.district = areaData.value[0]?.name || "";
};

function changeArea(e: any) {
  const temp = areaData.value.find(item => item.name === e);
  formTemp.value.cityCode = temp.code || "";
  // 获取到街道的数据
  // let jdData = areaData.value.filter((item) => item.name == e)[0].children;
  // console.log(jdData);
};
</script>

<style lang="scss" scoped>
.el-row {
  display: inline-flex;
  flex: auto;

  .el-select {
    margin: 0 20px 0 0;
    width: 122px;
  }
}
</style>
